package com.huichenghe.xinlvsh01.slide;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.LabeledIntent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huichenghe.xinlvsh01.Adapter.MYRecyclerAdapter;
import com.huichenghe.xinlvsh01.Ble.BleDataForCustomRemind;
import com.huichenghe.xinlvsh01.R;
import com.huichenghe.xinlvsh01.Utils.DataSecletor.NumericWheelAdapter;
import com.huichenghe.xinlvsh01.Utils.DataSecletor.WheelView;
import com.huichenghe.xinlvsh01.Utils.FormatUtils;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;
import com.huichenghe.xinlvsh01.Utils.MyToastUitls;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class SubCustonRemindActivity extends AppCompatActivity
{
    public static final String TAG = SubCustonRemindActivity.class.getSimpleName();
    private ImageView chooseType, chooseTime, chooseRepeat;
    private RelativeLayout mMove, mMedicine, mDrink, mSleep, mEat, mCustom, mShowTime;
    private LinearLayout mLinearLayout, mWeekSelect;
    private TextView showType, showTime, showRepeat, addTime;
    private TranslateAnimation a;
    private Button selectTimeOk, okToSend;
    private EditText editCustomName;
    private boolean isShowingChooseDialog = false;
    private boolean isShowingTime = false;
    private boolean isShowingWeek = false;
    private PopupWindow mPopupWindow;
    private ArrayList<String> timeList ;
    private RecyclerView recyclerView;
    private MYRecyclerAdapter myRecyclerAdapter;
    private CheckBox sunday, tuesday, monday, wednesday, thursday, saturday, friday;
    byte[] dataNO;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub_custon_remind);
        initToobar();
        intiView();

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        dataNO = getIntent().getByteArrayExtra(MyConfingInfo.SEND_TO_THE_ACTIVITY);
        Log.i(TAG, "提醒编号：" + FormatUtils.bytesToHexString(dataNO));



    }

    private void intiView()
    {
        okToSend = (Button)findViewById(R.id.ok_to_send_custom_remind);
        okToSend.setOnClickListener(listenterForChoose);


        timeList = new ArrayList<String>();
        myRecyclerAdapter = new MYRecyclerAdapter(SubCustonRemindActivity.this, timeList);
        chooseType = (ImageView)findViewById(R.id.choose_type_img);
        chooseTime = (ImageView)findViewById(R.id.choose_time_img);
        chooseRepeat = (ImageView)findViewById(R.id.choose_repeat_img);
        chooseType.setOnClickListener(listenterForChoose);
        chooseTime.setOnClickListener(listenterForChoose);
        chooseRepeat.setOnClickListener(listenterForChoose);

        mLinearLayout = (LinearLayout)findViewById(R.id.choose_layout_movement);
        mShowTime = (RelativeLayout)findViewById(R.id.show_time_layout);

        mMove = (RelativeLayout)findViewById(R.id.item_movement);
        mMedicine = (RelativeLayout)findViewById(R.id.item_take_medicine);
        mDrink = (RelativeLayout)findViewById(R.id.item_drink);
        mSleep = (RelativeLayout)findViewById(R.id.item_sleep);
        mEat = (RelativeLayout)findViewById(R.id.item_eat);
        mCustom = (RelativeLayout)findViewById(R.id.item_custom);
        mMove.setOnClickListener(listenterForChoose);
        mMedicine.setOnClickListener(listenterForChoose);
        mDrink.setOnClickListener(listenterForChoose);
        mSleep.setOnClickListener(listenterForChoose);
        mEat.setOnClickListener(listenterForChoose);
        mCustom.setOnClickListener(listenterForChoose);

        showType = (TextView)findViewById(R.id.show_the_type);
        showTime = (TextView)findViewById(R.id.show_the_time);
        showRepeat = (TextView)findViewById(R.id.show_the_repeat);
        addTime = (TextView)findViewById(R.id.add_custom_time);
        addTime.setOnClickListener(listenterForChoose);

        recyclerView = (RecyclerView)findViewById(R.id.rv_showTime);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(SubCustonRemindActivity.this));
        recyclerView.setAdapter(myRecyclerAdapter);

        selectTimeOk = (Button)findViewById(R.id.select_time_ok);
        selectTimeOk.setOnClickListener(listenterForChoose);

        mWeekSelect = (LinearLayout)findViewById(R.id.week_select);

        sunday = (CheckBox)findViewById(R.id.sunday);
        tuesday = (CheckBox)findViewById(R.id.tuesday);
        monday = (CheckBox)findViewById(R.id.monday);
        wednesday = (CheckBox)findViewById(R.id.wednesday);
        thursday = (CheckBox)findViewById(R.id.thurday);
        saturday = (CheckBox)findViewById(R.id.saturday);
        friday = (CheckBox)findViewById(R.id.friday);
        sunday.setOnCheckedChangeListener(new checkListener());
        tuesday.setOnCheckedChangeListener(new checkListener());
        monday.setOnCheckedChangeListener(new checkListener());
        wednesday.setOnCheckedChangeListener(new checkListener());
        thursday.setOnCheckedChangeListener(new checkListener());
        saturday.setOnCheckedChangeListener(new checkListener());
        friday.setOnCheckedChangeListener(new checkListener());



    }


    StringBuffer bufferS = new StringBuffer();
//    ArrayList<String> listWeek = new ArrayList<String>(7);
    String[] listWeek = new String[]{"无", "无", "无", "无", "无", "无", "无"};

    class checkListener implements CompoundButton.OnCheckedChangeListener
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if(bufferS.length() != 0)
            {
                bufferS.delete(0, bufferS.length());
            }

            switch (buttonView.getId())
            {
                case R.id.sunday:
                    if(isChecked)
                    {
                        listWeek[0] = getString(R.string.sunday);
                    }
                    else
                    {
                        listWeek[0] = "无";
                    }
                    break;
                case R.id.tuesday:
                    if(isChecked)
                    {
                        listWeek[1] = getString(R.string.monday);
                    }
                    else
                    {
                        listWeek[1] = "无";
                    }
                    break;
                case R.id.monday:
                    if(isChecked)
                    {
                        listWeek[2] = getString(R.string.tuesday);
                    }
                    else
                    {
                        listWeek[2] = "无";
                    }
                    break;
                case R.id.wednesday:
                    if(isChecked)
                    {
                        listWeek[3] = getString(R.string.wednesday);
                    }
                    else
                    {
                        listWeek[3] = "无";
                    }
                    break;
                case R.id.thurday:
                    if(isChecked)
                    {
                        listWeek[4] = getString(R.string.thursday);
                    }
                    else
                    {
                        listWeek[4] = "无";
                    }
                    break;
                case R.id.saturday:
                    if(isChecked)
                    {
                        listWeek[5] = getString(R.string.friday);
                    }
                    else
                    {
                        listWeek[5] = "无";
                    }
                    break;
                case R.id.friday:
                    if(isChecked)
                    {
                        listWeek[6] = getString(R.string.saturday);
                    }
                    else
                    {
                        listWeek[6] = "无";
                    }
                    break;
            }
            int count = 0;
            for (int i = 0; i < listWeek.length; i ++)
            {
                String s = listWeek[i];
                Log.i(TAG, "当前周：" + s);
                if(!s.equals("无"))
                {
                    count ++;
                    bufferS.append(s);
                    bufferS.append("/");

                }
            }

            String aa;
            if(count == 7)
            {
                aa = getString(R.string.everyday);
            }
            else
            {
                aa = bufferS.toString().trim();
                if(aa != null)
                {
                    if(aa.length() > 2)
                    {
                        aa = aa.substring(0, bufferS.length() - 1);
                    }
                }


                if(aa == null || aa.equals(""))
                {
                    aa = getString(R.string.only_once);
                }
            }

            Log.i(TAG, "当前字符串：" + aa);
            showRepeat.setText(aa);

        }
    }

    byte typeInInt;
    View.OnClickListener listenterForChoose = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.choose_type_img:
                    // 显示选择提醒类型
                    // 执行动画
                    mLinearLayout.setVisibility(View.VISIBLE);
                    a = new TranslateAnimation(0, 0, mLinearLayout.getHeight(), 0);
                    a.setDuration(500);
                    mLinearLayout.setAnimation(a);
                    a.startNow();
                    isShowingChooseDialog = true;

                    break;
                case R.id.choose_time_img:
                    mShowTime.setVisibility(View.VISIBLE);
                    a = new TranslateAnimation(0, 0, mShowTime.getHeight(), 0);
                    a.setDuration(500);
                    mShowTime.setAnimation(a);
                    a.start();
                    isShowingTime = true;
                    break;
                case R.id.choose_repeat_img:
                    int isShow = mWeekSelect.getVisibility();// 获取控件是否隐藏或显示
                    if(isShow == View.VISIBLE)
                    {
                        mWeekSelect.setVisibility(View.GONE);
                    }
                    else
                    {
                        mWeekSelect.setVisibility(View.VISIBLE);
                    }



                    break;
                case R.id.item_movement:
                    //  点击运动选择
                    // 隐藏布局
                    a.cancel();
                    mLinearLayout.setVisibility(View.GONE);
                    showType.setText(getString(R.string.movement_text));
                    typeInInt = (byte)0x01;

                    break;
                case R.id.item_take_medicine:
                    a.cancel();
                    mLinearLayout.setVisibility(View.GONE);
                    showType.setText(getString(R.string.take_medicine));
                    typeInInt = (byte)0x04;


                    break;
                case R.id.item_drink:
                    a.cancel();
                    mLinearLayout.setVisibility(View.GONE);
                    showType.setText(getString(R.string.drink));
                    typeInInt = (byte)0x03;


                    break;
                case R.id.item_sleep:
                    a.cancel();
                    mLinearLayout.setVisibility(View.GONE);
                    showType.setText(getString(R.string.sleep_text_choose));
                    typeInInt = (byte)0x05;


                    break;
                case R.id.item_eat:
                    a.cancel();
                    mLinearLayout.setVisibility(View.GONE);
                    showType.setText(getString(R.string.eat_foot));
                    typeInInt = (byte)0x02;


                    break;
                case R.id.item_custom:
                    // 点击编辑
                    a.cancel();
                    mLinearLayout.setVisibility(View.GONE);
                    AlertDialog.Builder dialog = new AlertDialog.Builder(SubCustonRemindActivity.this);
                    View view = LayoutInflater.from(SubCustonRemindActivity.this).inflate(R.layout.edit_custom_layout, null);
                    dialog.setView(view);
                    editCustomName = (EditText)view.findViewById(R.id.edit_custom_name);
                    dialog.setPositiveButton(getString(R.string.be_true), new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String name = editCustomName.getText().toString().trim();
                            showType.setText(name);
                            dialog.dismiss();
                        }
                    });
                    dialog.setNegativeButton(getString(R.string.be_cancle), null);
                    dialog.create().show();

                    typeInInt = (byte)0x06;


                    break;

                case R.id.add_custom_time:
                    // 显示时间选择器

                    showPopWindow(getTimePick());
                    break;
                case R.id.select_time_ok:
                    // 点击完成时间选择,将用户选择内容显示到showTime上
                    StringBuffer buffer = new StringBuffer();
                    if(timeList.size() != 0)
                    {
                        for (int i = 0; i < timeList.size(); i++)
                        {
                            // 遍历集合
                            String s = timeList.get(i);
                            if(s != null && !s.equals(""))
                            {
                                buffer.append(s);
                                buffer.append("/");
                            }

                        }
                        showTime.setText(buffer.toString().trim().substring(0, buffer.length() - 1));
                    }

                    mShowTime.setVisibility(View.GONE);




                    break;

                case R.id.ok_to_send_custom_remind:
                    // 确定编辑完成，并发送数据到手环
                    String typeName = showType.getText().toString().trim();
                    String typeTime = showTime.getText().toString().trim();
                    String typeRepeat = showRepeat.getText().toString().trim();
                    // 先进行非空验证
                    boolean isOk = juageTheInput(typeName, typeTime, SubCustonRemindActivity.this);
//                    String timeS = timeList;
//                    String repeatS = listWeek;

                    if(isOk)
                    {
                        if(typeInInt == 6)
                        {
                            try
                            {
                                byte[] bytess = typeName.getBytes("GB2312");
                                byteToSend = new byte[2 + bytess.length + 3 + 2 * timeList.size() ];
                            } catch (UnsupportedEncodingException e)
                            {
                                e.printStackTrace();
                            }

                        }
                        else
                        {
                            byteToSend = new byte[2 + timeList.size() + 3 + 1];
                        }
                        // 星期的一个字节
                        byte b = 0;
                        int a = 0;
                        for (int i = 0; i < 7; i ++)
                        {
                            String s = listWeek[i];
                            if(!s.equals("无"))
                            {
                                if(i > 0)
                                {
                                    if(i == 7)
                                    {
                                        b |= (byte)0x01;
                                    }
                                    else
                                    {
                                        b |= ((byte)0x01 << i);
                                    }
                                }
                            }
                        }

                        // 运动类型
                        // 提醒时间点总数
                        int tim = timeList.size();
                        byte times = (byte)(tim & 0xff) ;


                        // 提醒时间
                        byte[] bbb = new byte[tim * 2];
                        for (int i = 0; i < bbb.length; i += 2)
                        {
                            String sub = timeList.get(i);
                            String hour = sub.substring(0, 2);
                            String minute = sub.substring(3);
                            int hourI = Integer.parseInt(hour);
                            int minuteI = Integer.parseInt(minute);
                            byte hourB = (byte)(hourI & 0xff);
                            byte minuteB = (byte)(minuteI & 0xff);

                            bbb[i] = hourB;
                            bbb[i + 1] = minuteB;
                        }


                        // 提醒编号
                        int length = dataNO.length;
//                        dataNO[length] = (byte)(length * 0xff);
                        /**
                         * 整合数据
                         */
                        int index = 0;
                            byteToSend[index] = 0x01;   index ++;                    // 整合设置

                            byteToSend[index] = (byte)(length & 0xff);   index ++;   // 整合此条提醒的编号

                        // 整合提醒类型

                        byteToSend[index] = (byte)(typeInInt & 0xff);   index ++;




                        // 整合提醒时间总数

                        byteToSend[index] = times;  index ++;

                        // 整合提醒时间

                        for (int i = 0; i < bbb.length; i ++)
                        {
                            Log.i(TAG, "提醒时间在循环中：" + FormatUtils.bytesToHexString(bbb) + byteToSend.length);
                            byteToSend[i + index] = bbb[i];

                            index ++;
                        }

                        // 整合重复天
                        byteToSend[index] = (byte)b;
                        // 整合提醒名称，此部分数据只在自定义提醒名称时发送

                        if(typeInInt == 6)
                        {
                            try {                                       // 整合运动类型
                                byte[] bateName = typeName.getBytes("GB2312");
                                for (int j = 0; j < bateName.length; j ++)
                                {
                                    byteToSend[j + index] = bateName[j];
                                    index ++;
                                }
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }


                        // 数据整合完成，向手环发送
                        new BleDataForCustomRemind()
                                .setMsgToByteDataAndSendToDevice(
                                        BleDataForCustomRemind.toDevice,
                                        byteToSend, byteToSend.length, true);



                    }


                    break;
            }

        }
    };



    private boolean juageTheInput(String typeName, String typeTime, Context context)
    {
        if(typeName.length() == 0)
        {
            MyToastUitls.showToast(context, R.string.type_not_null, 2);
            return false;
        }
        if(typeTime.length() == 0)
        {
            MyToastUitls.showToast(context, R.string.time_not_null, 2);
            return false;
        }
        return true;
    }

    byte[] byteToSend;
    /**
     * 在popwindow里显示指定的view
     * @param timePick
     */
    private void showPopWindow(View timePick)
    {
        mPopupWindow = new PopupWindow(
                timePick, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.showAtLocation(timePick, Gravity.CENTER_HORIZONTAL, 0, 0);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener()
        {
            @Override
            public void onDismiss()
            {
                mPopupWindow = null;
            }
        });



    }


    /**
     * 时间选择器布局
     * @return
     */
    private View getTimePick()
    {
        View view = LayoutInflater.from(SubCustonRemindActivity.this).inflate(R.layout.timepick, null);
        final WheelView hour = (WheelView)view.findViewById(R.id.hour);
        hour.setAdapter(new NumericWheelAdapter(0, 23, "%02d"));
        hour.setLabel(getString(R.string.hour_wheel));
        hour.setCyclic(true);
        final WheelView minute = (WheelView)view.findViewById(R.id.mins);
        minute.setAdapter(new NumericWheelAdapter(0, 59, "%02d"));
        minute.setLabel(getString(R.string.minute_wheel));
        minute.setCyclic(true);

        hour.setCurrentItem(8);
        minute.setCurrentItem(30);

        Button bt = (Button)view.findViewById(R.id.set);
        Button ancel = (Button)view.findViewById(R.id.cancel);
        bt.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String h = String.valueOf(hour.getCurrentItem());
                String m = String.valueOf(minute.getCurrentItem());
                if (h.length() == 1)
                {
                    h = "0" + h;
                }
                if(m.length() == 1)
                {
                    m = "0" + m;
                }
                String str = h + ":" + m;
                timeList.add(str);
                myRecyclerAdapter.notifyDataSetChanged();
                mPopupWindow.dismiss();

            }
        });

        ancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });


        return view;


    }


    private void initToobar()
    {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.custom_remind);
        toolbar.setTitleTextColor(getResources().getColor(R.color.White_forme));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationIcon(R.drawable.back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SubCustonRemindActivity.this.onBackPressed();
            }
        });

    }










    // 对虚拟键操作
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(isShowingChooseDialog)
            {
                a.cancel();
                mLinearLayout.setVisibility(View.GONE);
                isShowingChooseDialog = false;
                return true;
            }
            if(isShowingTime)
            {
                a.cancel();
                mShowTime.setVisibility(View.GONE);
                isShowingTime = false;
                return true;
            }


        }






        return super.onKeyDown(keyCode, event);
    }
}
